#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <sys/wait.h> 
using namespace std;
#define BUFFER_SIZE 16
int main()
{   
    const char * fileName = "./fifoInfo";
    int ret = mkfifo(fileName,0644);
    if(ret != 0)
    {
        perror("mkfifo error:");
        exit(-1);
    }
    pid_t pid = fork();
    if(pid > 0)
    {
        printf("parent process\n");

        int fd = open(fileName,O_WRONLY);
        if(fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }

        int cnt = 3;
        const char *buf = "hello world";

        int writeBytes = 0;
        while(cnt--)
        {   
            writeBytes = write(fd,buf,strlen(buf));
            if(writeBytes > 0)
            {
                cout<<"writeBytes:"<<writeBytes<<endl;
            }
            else if(writeBytes = 0)
            {
                cout<<"writeBytes == "<<endl;
            }
            else if(writeBytes < 0)
            {
                perror("write error:");
            }
        }
        close(fd);
        wait(NULL);
    }
    else if(pid == 0)
    {
        int fd = open(fileName,O_RDWR);
        if(fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }

        int flags =fcntl(fd,F_GETFL);

        //设置文件描述符为非阻塞
        fcntl(fd,F_SETFL,flags | O_NONBLOCK);
        char buffer[BUFFER_SIZE] = {0};

        int readBytes = 0;
        while(1)
        {   
            sleep(3);
            readBytes = read(fd,buffer,sizeof(buffer)-1);
            if(readBytes > 0)
            {
                printf("readBytes = %d,\t buffer = %s\n",readBytes,buffer);
            }
            else if(readBytes == 0)
            {
                cout<<"readBytes == 0"<<endl;
                break;
            }
            else if(readBytes < 0)
            {   
                if(errno == EAGAIN)
                {
                    cout<<"errno == EAGAIN"<<endl;
                    break;
                }
                else
                {
                    perror("read error");
                    close(fd);
                    _exit(-1);
                }
                cout<<"readBytes < 0"<<endl;
                break;
            }
            sleep(1);
            memset(buffer,0,sizeof(buffer));
        } 
    }
    else
    {

    }
}